package com.clearliang.wxredpacket.redPacketService;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.clearliang.wxredpacket.R;

import java.util.List;

/**
 * Created by ClearLiang on 2019/1/7
 * <p>
 * Function :<p>
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyAccessibilityServiceCopy extends AccessibilityService {
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
    }

    //(必要)当系统监测到相匹配的AccessibilityEvent事件时，将调用此方法，在整个Service的生命周期中，该方法将被多次调用。
    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        final String packageName = "com.tencent.mm";
        //AccessibilityOperator.getInstance().updateEvent(this, accessibilityEvent);
        //LogUtils.e("我点击了", JSON.toJSONString(accessibilityEvent));
        /*if(accessibilityEvent.getPackageName().equals(packageName)){
            LogUtils.e("我点击了");

            Intent intent= new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用,必须加入new task标识
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    ActivityManager activityMgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
                    if (activityMgr != null) {
                        activityMgr.killBackgroundProcesses(packageName);
                        ToastUtils.showShort("禁止启动该APP");
                    }else {
                        ToastUtils.showShort("获取ActivityManager失败");
                    }

                }
            },1000);
        }*/
        int eventType = accessibilityEvent.getEventType();
        Log.e("时间码", String.valueOf(eventType));
        switch (eventType) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                handleNotification(accessibilityEvent);
                break;
            case AccessibilityEvent.TYPE_VIEW_SELECTED:
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
            case AccessibilityEvent.TYPE_VIEW_SCROLLED:
                String className = accessibilityEvent.getClassName().toString();
                Log.e("类名", className);
                switch (className) {
                    case "com.tencent.mm.ui.LauncherUI":
                        //getPacket();
                        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                        findRedPacket(nodeInfo);
                        break;
                    case "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyReceiveUI":
                        openPacket();
                        break;
                    case "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI":
                        close();
                        break;
                    case "com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyNotHookReceiveUI":
                        Log.e("信息","打开红包");
                        openPacket();
                        break;
                }
                break;
        }
    }

    /**
     * 处理通知栏信息
     * 如果是微信红包的提示信息,则模拟点击
     */
    private void handleNotification(AccessibilityEvent event) {
        List<CharSequence> texts = event.getText();
        if (!texts.isEmpty()) {
            for (CharSequence text : texts) {
                String content = text.toString();
                //如果微信红包的提示信息,则模拟点击进入相应的聊天窗口
                if (content.contains("[微信红包]")) {
                    if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {
                        isOpenRP = false;
                        Notification notification = (Notification) event.getParcelableData();
                        PendingIntent pendingIntent = notification.contentIntent;
                        try {
                            pendingIntent.send();
                        } catch (PendingIntent.CanceledException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    /**
     * 关闭红包详情界面,实现自动返回聊天窗口
     */
    private void close() {
        //返回桌面
        back2Home();

        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            //为了演示,直接查看了关闭按钮的id
            List<AccessibilityNodeInfo> infos = nodeInfo.findAccessibilityNodeInfosByViewId("@id/ez");
            nodeInfo.recycle();
            for (AccessibilityNodeInfo item : infos) {
                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    }

    /**
     * 返回桌面
     */
    private void back2Home() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

    /**
     * 模拟点击,拆开红包
     */
    private void openPacket() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            //为了演示,直接查看了红包控件的id
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(getResources().getString(R.string.wx_packet_open));
            nodeInfo.recycle();
            for (AccessibilityNodeInfo item : list) {
                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }
    }

    /**
     * 模拟点击,打开抢红包界面
     */
    private void getPacket() {
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        //AccessibilityNodeInfo originNode = rootNode;
        AccessibilityNodeInfo node = recycle(rootNode);

        node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        AccessibilityNodeInfo parent = node.getParent();
        while (parent != null) {
            if (parent.isClickable()) {
                parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                break;
            }
            parent = parent.getParent();
        }

    }

    private void getPacket1() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();


        if (nodeInfo != null) {
            //为了演示,直接查看了红包控件的id
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/ao4");
            nodeInfo.recycle();
            for (AccessibilityNodeInfo item : list) {
                item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
            }
        }

    }

    /**
     * 遍历查找红包
     */
    private boolean isOpenRP;   //用于判断是否点击过红包了

    /**
     * 遍历查找红包
     */
    private void findRedPacket(AccessibilityNodeInfo rootNode) {
        if (rootNode != null) {
            //从最后一行开始找起
            for (int i = rootNode.getChildCount() - 1; i >= 0; i--) {
                AccessibilityNodeInfo node = rootNode.getChild(i);
                //如果node为空则跳过该节点
                if (node == null) {
                    continue;
                }
                CharSequence text = node.getText();

                if (text != null && text.toString().equals("已领取")) {
                    isOpenRP = true;
                } else if (text != null && text.toString().equals("微信红包")) {
                    AccessibilityNodeInfo parent = node.getParent();
                    //while循环,遍历"领取红包"的各个父布局，直至找到可点击的为止
                    while (parent != null) {
                        if (parent.isClickable()) {
                            //模拟点击
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            //isOpenRP用于判断该红包是否点击过
                            isOpenRP = true;
                            break;
                        }
                        parent = parent.getParent();
                    }
                }

                //判断是否已经打开过那个最新的红包了，是的话就跳出for循环，不是的话继续遍历
                if (isOpenRP) {
                    break;
                } else {
                    findRedPacket(node);
                }

            }
        }
    }

    /**
     * 递归查找当前聊天窗口中的红包信息
     * 聊天窗口中的红包都存在"领取红包"一词,因此可根据该词查找红包
     */
    public AccessibilityNodeInfo recycle(AccessibilityNodeInfo node) {

        if (node.getChildCount() == 0) {
            if (node.getText() != null) {
                if ("微信红包".equals(node.getText().toString())) {
                    return node;
                }
            }
        } else {
            for (int i = 0; i < node.getChildCount(); i++) {
                if (node.getChild(i) != null) {
                    recycle(node.getChild(i));
                }
            }
        }
        return node;
    }

    public boolean recycle1(AccessibilityNodeInfo node) {

        if (node.getChildCount() == 0) {
            if (node.getText() != null) {
                if ("微信红包".equals(node.getText().toString())) {
                    return true;
                }
            }
        } else {
            for (int i = 0; i < node.getChildCount(); i++) {
                if (node.getChild(i) != null) {
                    recycle1(node.getChild(i));
                }
            }
        }
        return false;
    }

    //(必要)系统需要中断AccessibilityService反馈时，将调用此方法。AccessibilityService反馈包括服务发起的震动、音频等行为
    @Override
    public void onInterrupt() {

    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}
